package com.example.forum2.services.impl;

import com.example.forum2.common.AppResult;
import com.example.forum2.common.ResultCode;
import com.example.forum2.dao.ArticleReplyMapper;
import com.example.forum2.exception.ApplicationException;
import com.example.forum2.model.ArticleReply;
import com.example.forum2.services.IArticleReplyService;
import com.example.forum2.services.IArticleService;
import com.example.forum2.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ArticleReplyServiceImpl implements IArticleReplyService {
    @Resource
    private ArticleReplyMapper articleReplyMapper;
    @Resource
    private IArticleService articleService;
    @Override
    public void createReplyArticle(ArticleReply articleReply) {
//        首先对参数进行校验
        if(articleReply==null || StringUtil.isEmpty(articleReply.getContent()) ||articleReply.getArticleId()==null
           ||articleReply.getPostUserId()==null){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
//        设置默认值
        articleReply.setReplyId(null);
        articleReply.setReplyUserId(null);
        articleReply.setLikeCount(0);
        articleReply.setState((byte)0);
        articleReply.setDeleteState((byte)0);
        Date date=new Date();
        articleReply.setCreateTime(date);
        articleReply.setUpdateTime(date);
        int row=articleReplyMapper.insertSelective(articleReply);
//        对返回值进行校验
        if(row!=1){
//            打印日志
            log.warn(ResultCode.ERROR_SERVICES.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }
//        对文章的回复数进行+1操作
        articleService.addOneReplyCountById(articleReply.getArticleId());
    }

    @Override
    public List<ArticleReply> selectByArticleId(Long articleId) {
//        首先还是进行参数校验
        if(articleId==null||articleId<=0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
//        调用dao
        List<ArticleReply> articleReplies=articleReplyMapper.selectByArticleId(articleId);
//        返回结果
        return articleReplies;
    }
}
